<?php

namespace App\Http\Controllers\Notify;

use App\Enums\OrderEnum;
use App\Http\Controllers\BaseController;
use App\Http\Logic\OrderLogic;
use App\Services\WechatPayService;
use Dingo\Api\Http\Request;
use Illuminate\Support\Facades\Log;

class WechatNotifyController extends BaseController
{

    /**
     * @notes 微信支付分回调
     * @param Request $request
     * @return \Dingo\Api\Http\Response
     * @author Evil丿
     * @date 2024/04/17 09:52
     */
    public function wechatOrder(Request $request)
    {
        $signature = $request -> header('wechatpay-signature');

        $timestamp = $request -> header('wechatpay-timestamp');

        $nonce = $request -> header('wechatpay-Nonce');

        $body = $request -> getContent();

        $header = $request->header();

        $service = new WechatPayService();

        $params = $service -> verifySign($signature, $timestamp, $nonce, $body);

        if(empty($params)) {
            Log::channel('wechat')->error('wechatOrder', ['header' => $header]);

            return $this->error('验签失败','FAIL');
        }

        switch ($params["state"]) {
            case OrderEnum::ORDER_DOING : //授权成功回调
                $res = true;
                break;
            case OrderEnum::ORDER_DONE : //支付成功回调
                $res = OrderLogic::finishOrder($params,'wechat');
                break;
            default:
                $res = true;
                break;
        }

        if($res !== true) {
            Log::channel('wechat')->error('wechatOrder', ['params' => $params, 'error' => $res]);

            return $this->error($res,'FAIL');
        }

        return $this->success([],'','SUCCESS');
    }

    /**
     * @notes 微信支付订单回调
     * @param Request $request
     * @return \Dingo\Api\Http\Response
     * @author Evil丿
     * @date 2024/08/06 13:26
     */
    public function wechatJsApiOrder(Request $request){
        $signature = $request -> header('wechatpay-signature');

        $timestamp = $request -> header('wechatpay-timestamp');

        $nonce = $request -> header('wechatpay-Nonce');

        $body = $request -> getContent();

        $header = $request->header();

        $service = new WechatPayService();

        $params = $service -> verifySign($signature, $timestamp, $nonce, $body);

        if(empty($params)) {
            Log::channel('wechat')->error('wechatJsApiOrder', ['header' => $header]);

            return $this->error('验签失败','FAIL');
        }

        $res = OrderLogic::finishAmountErrorOrder($params,'wechat');

        if($res !== true) {
            Log::channel('wechat')->error('wechatJsApiOrder', ['params' => $params, 'error' => $res]);

            return $this->error($res,'FAIL');
        }

        return $this->success([],'','SUCCESS');
    }
}
